
import { Constructor } from "cc";
import { ECSEntity } from "./ECSEntity";
import { ECSCmp } from "./ECSComp";

/**
 * 实体过滤器接口
 */
export interface IEntityFilter {
    /** 检查实体是否符合过滤条件 */
    match(entity: ECSEntity): boolean;
}

/**
 * 组件过滤器 - 要求实体包含指定组件
 */
export class ComponentFilter implements IEntityFilter {
    private _requiredComponents: Constructor<ECSCmp>[];

    constructor(requiredComponents: Constructor<ECSCmp>[]) {
        this._requiredComponents = requiredComponents;
    }

    match(entity: ECSEntity): boolean {
        if (this._requiredComponents.length === 0) return false;
        return this._requiredComponents.every(cmp => entity.hasComponent(cmp));
    }
}

/**
 * 组件过滤器 - 要求实体是enable
 */
export class EnableFilter implements IEntityFilter {
    match(entity: ECSEntity): boolean {
        return entity.enable
    }
}

/**
 * 标签过滤器 - 要求实体包含指定标签
 */
export class TagFilter implements IEntityFilter {
    private _requiredTags: string[];

    constructor(requiredTags: string[]) {
        this._requiredTags = requiredTags;
    }

    match(entity: ECSEntity): boolean {
        if (this._requiredTags.length === 0) return false
        return this._requiredTags.every(tag => entity.hasTag(tag))
    }
}

/**
 * 排除标签过滤器 - 要求实体不包含指定标签
 */
export class ExcludeTagFilter implements IEntityFilter {
    private _excludedTags: string[];

    constructor(excludedTags: string[]) {
        this._excludedTags = excludedTags;
    }

    match(entity: ECSEntity): boolean {
        if (this._excludedTags.length === 0) return false
        return this._excludedTags.every(tag => !entity.hasTag(tag))
    }

    getDescription(): string {
        return `Excluded Tags: [${this._excludedTags.join(', ')}]`;
    }

    getExcludedTags(): string[] {
        return [...this._excludedTags];
    }
}

/**
 * 复合过滤器 - 组合多个过滤器
 */
export class CompositeFilter implements IEntityFilter {
    private _filters: IEntityFilter[];
    private _operator: 'AND' | 'OR';

    constructor(filters: IEntityFilter[], operator: 'AND' | 'OR' = 'AND') {
        this._filters = [...filters];
        this._operator = operator;
    }

    match(entity: ECSEntity): boolean {
        // 没有过滤器的情况全部通过
        if (this._filters.length === 0) return true;

        if (this._operator === 'AND') {
            return this._filters.every(filter => filter.match(entity));
        } else {
            return this._filters.some(filter => filter.match(entity));
        }
    }

    addFilter(filter: IEntityFilter): void {
        this._filters.push(filter);
    }

    removeFilter(filter: IEntityFilter): void {
        const index = this._filters.indexOf(filter);
        if (index >= 0) {
            this._filters.splice(index, 1);
        }
    }
}

